package com.nineclock.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nineclock.attendance.dto.DepartmentOrUserSimpleDTO;
import com.nineclock.common.enums.ResponseEnum;
import com.nineclock.common.exception.NcException;
import com.nineclock.common.threadlocal.CurrentUserHolder;
import com.nineclock.common.utils.BeanHelper;
import com.nineclock.system.dto.SysDepartmentDTO;
import com.nineclock.system.mapper.SysCompanyUserMapper;
import com.nineclock.system.mapper.SysDepartmentMapper;
import com.nineclock.system.pojo.SysCompanyUser;
import com.nineclock.system.pojo.SysDepartment;
import com.nineclock.system.service.SysDepartmentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 黑马程序员
 * @Company http://www.ithiema.com
 * @Version 1.0
 */
@Slf4j
@Service
public class SysDepartmentServiceImpl implements SysDepartmentService {

    @Autowired
    SysDepartmentMapper departmentMapper;

    @Autowired
    SysCompanyUserMapper companyUserMapper;


    @Override
    public List<SysDepartmentDTO> queryDepartmentList() {
        List<SysDepartmentDTO> departmentDTOList = this.queryChildDepartmentList(0L);
        return departmentDTOList;
    }

    @Override
    public List<Long> queryDepartmentIds() {
        Long companyId = CurrentUserHolder.get().getCompanyId();
        LambdaQueryWrapper<SysDepartment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysDepartment::getCompanyId, companyId);
        wrapper.eq(SysDepartment::getParentId, 0);

        List<SysDepartment> departmentList = departmentMapper.selectList(wrapper);
        //取出部门列表中的id
        List<Long> ids = departmentList.stream().map(department -> {
            return department.getId();
        }).collect(Collectors.toList());


        return ids;
    }

    /**
     * 查询该部门的子部门及 员工列表
     * @param departmentId
     * @param includeMember
     * @return
     */
    @Override
    public List<DepartmentOrUserSimpleDTO> querySimpleDepartment(Long departmentId, Integer includeMember) {
        //创建返回值对象
        List<DepartmentOrUserSimpleDTO> list = new ArrayList<>();

        if(departmentId == null || includeMember == null){
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }

        //查询该部门对应的子部门
        LambdaQueryWrapper<SysDepartment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysDepartment::getCompanyId, CurrentUserHolder.get().getCompanyId());
        wrapper.eq(SysDepartment::getParentId, departmentId);
        List<SysDepartment> departmentList = departmentMapper.selectList(wrapper);
        if(CollectionUtil.isNotEmpty(departmentList)){
            for (SysDepartment department : departmentList) {
                //创建 返回值 对应的对象
                DepartmentOrUserSimpleDTO departmentSimpleDTO = new DepartmentOrUserSimpleDTO();
                departmentSimpleDTO.setType(1);
                departmentSimpleDTO.setId(department.getId());
                departmentSimpleDTO.setName(department.getName());
                list.add(departmentSimpleDTO);
            }
        }


        if(includeMember == 0){
            LambdaQueryWrapper<SysCompanyUser> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(SysCompanyUser::getCompanyId, CurrentUserHolder.get().getCompanyId());
            wrapper1.eq(SysCompanyUser::getDepartmentId, departmentId);
            List<SysCompanyUser> companyUserList = companyUserMapper.selectList(wrapper1);
            if(CollectionUtil.isNotEmpty(companyUserList)){
                for (SysCompanyUser companyUser : companyUserList) {
                    DepartmentOrUserSimpleDTO userSimpleDTO = new DepartmentOrUserSimpleDTO();
                    userSimpleDTO.setType(2);
                    userSimpleDTO.setId(companyUser.getId());
                    userSimpleDTO.setName(companyUser.getUserName());
                    list.add(userSimpleDTO);
                }
            }
        }


        return list;
    }

    /**
     * 1. 根据用户id 获取所在部门
     * 2. 根据部门id获取上级部门id
     * 3. 循环查询上级的上级， 结束条件（parentId = 0 ）
     * @param companyUserId
     * @return
     */
    @Override
    public List<Long> queryDepartmentsByUserId(Long companyUserId) {
        List<Long> ids = new ArrayList<>();

        //查询该员工所在部门id
        LambdaQueryWrapper<SysCompanyUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysCompanyUser::getCompanyId, CurrentUserHolder.get().getCompanyId());
        wrapper.eq(SysCompanyUser::getId, companyUserId);
        SysCompanyUser companyUser = companyUserMapper.selectOne(wrapper);
        if(companyUser == null){
            throw new NcException(ResponseEnum.USER_NOT_FOUND);
        }
        //获取员工所在的部门id
        Long departmentId = companyUser.getDepartmentId();
        ids.add(departmentId);


        while (true){
            //查询该部门的上级部门
            LambdaQueryWrapper<SysDepartment> departmentQw = new LambdaQueryWrapper<>();
            departmentQw.eq(SysDepartment::getCompanyId, CurrentUserHolder.get().getCompanyId());
            departmentQw.eq(SysDepartment::getId, departmentId);
            SysDepartment department = departmentMapper.selectOne(departmentQw);
            if(department != null){
                //获取上级id
                Long parentId = department.getParentId();
                if(parentId == 0){
                    break;
                }
                ids.add(parentId);
                departmentId = parentId;
            }
        }

        return ids;
    }


    public List<SysDepartmentDTO> queryChildDepartmentList(Long parentId){
        //获取当前登录用户的企业id
        Long companyId = CurrentUserHolder.get().getCompanyId();
        //设置条件
        LambdaQueryWrapper<SysDepartment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysDepartment::getCompanyId, companyId);
        wrapper.eq(SysDepartment::getParentId, parentId); //0 表示 顶级部门
        //查询部门列表
        List<SysDepartment> departmentList = departmentMapper.selectList(wrapper);
        //如果不为null ， 查询子部门
        if(CollectionUtil.isNotEmpty(departmentList)) {
            List<SysDepartmentDTO> departmentDTOList = BeanHelper.copyWithCollection(departmentList, SysDepartmentDTO.class);
            for (SysDepartmentDTO departmentDTO : departmentDTOList) {
                //查询子部门列表信息
                List<SysDepartmentDTO> childDepartmentDTOList = this.queryChildDepartmentList(departmentDTO.getId());
                departmentDTO.setChildren(childDepartmentDTOList);
            }
            return departmentDTOList;
        }
        return new ArrayList<>();
    }
}
